//
//  WarehousePlateVC.m
//  ProjectforHDX
//
//  Created by lzg on 2017/8/12.
//  Copyright © 2017年 H.DX. All rights reserved.
//

#import "WarehousePlateVC.h"
#import "SearchBar.h" // 搜索框
#import "StockInquiryHeadView.h" // 自定义headView
#import "ShipmentReportHeadView.h" // 自定义headView
#import "StockInquiryCell.h" // 自定义cell
#import "ShipmentReportCell.h" // 自定义cell

#import "AFNetworking.h"

#import "PlateModel.h"

#import "StockInquryDetailVC.h"

#import "StockPopVIewController.h"

#import "MainVC.h"

#import "WarehouseHeadView.h"

#import "SerialNumberVC.h"

#import "WarehouseTotalVC.h"


typedef enum
{
    searchTypeFixpart=1,
    searchTypeFaultpart=2,
    searchTypeAll=3
}searchType;

@interface WarehousePlateVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,StockPopViewDelegate,UITextFieldDelegate> {
    /**
     *  cell数据 查询到的板件
     */
    NSArray *dataArr;
    StockPopVIewController *_popView;
    BOOL hiden;
    UIButton *_typeBtn;
    UIButton *_storeNameBtn;
    //库存获取信息的数组
    NSMutableArray *stockArr;
    
    NSInteger teger;
    NSInteger tag;
    
    UIDatePicker *datePicker;
    UIToolbar *toolBar;
    
    UIButton *startBut;
    UIButton *endBut;
    
    NSIndexPath *clicknumber;
}

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *coverView;

@property (nonatomic, strong) StockInquiryHeadView *headView;
@property (nonatomic, strong) WarehouseHeadView *warehouseHeadView;

//@property (nonatomic, assign) NSInteger *type;

@property (nonatomic, strong) UIView *searchHoldView;
/**
 *  网络请求参数
 */
@property (nonatomic, strong) NSMutableDictionary *postDict;
@property (nonatomic, strong) NSMutableDictionary *stockStrDict;
@property (nonatomic, strong) UIView *maskView;
@end

@implementation WarehousePlateVC
{
    BOOL showPop;
    
    RZCustomButtom *_numLab;
}

static int type=1;

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",_plateArr);
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    stockArr = [NSMutableArray array];
    type = 1;

    [_stockStrDict setValue:[THMangerTool getKey] forKey:@"Key"];
    [self setupDatas];
    [self setupViews];
}
#pragma mark 数据初始化

- (NSMutableDictionary *)postDict
{
    if (!_postDict) {
        _postDict = [NSMutableDictionary dictionary];
    }
    return _postDict;
}
- (void)setupDatas {
    dataArr = [NSArray array];
}



#pragma mark 视图初始化
- (void)setupViews {
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 64)];
    [headView setBackgroundColor:[UtilCheck hexStringToColor:@"#1A57BE" alpha:1]];
    [self.view addSubview:headView];
    
    UIButton *backBtn = [[UIButton alloc]init];
    [backBtn setFrame:CGRectMake(0, 20, 44, 44)];
    [backBtn addTarget:self action:@selector(backView) forControlEvents:UIControlEventTouchUpInside];
    backBtn.backgroundColor = [UtilCheck hexStringToColor:@"#1A57BE" alpha:1.0];
    [backBtn setImage:[UIImage imageNamed:@"ShipmentReportVC返回"] forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    
    UILabel *headLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, self.view.width, 44)];
    headLable.text = [UtilCheck language:@"main.shipmentReport"];
    headLable.textColor = [UIColor whiteColor];
    [headLable setFont:[UIFont systemFontOfSize:20]];
    headLable.textAlignment = UITextAlignmentCenter;
    [headView addSubview:headLable];
    {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.width, self.view.height - 64) style:(UITableViewStylePlain)];
        
        
        //warehouseHeadView
        self.warehouseHeadView = [[WarehouseHeadView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 90)];
        self.tableView.backgroundColor = [UtilCheck hexStringToColor:@"F5F7f8" alpha:1];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.tableHeaderView = self.warehouseHeadView;
        NSString *number = _plateCount;
        NSString *countStr = [NSString stringWithFormat:[UtilCheck language:@"setting.commonCount"],number];
        self.warehouseHeadView.titleLab.attributedText = [self attributedString:countStr];
        [self.view addSubview:self.tableView];

    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
}
//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification
{
    teger = 1;
}


- (void)backView
{
    AppDelegate * app = [UIApplication sharedApplication].delegate;
    app.shouldChangeOrientation = YES;
//    WarehouseTotalVC *vc = [[WarehouseTotalVC alloc]init];
//    vc.totalDic =
    [_plateDic setValue:@"" forKey:@"plateCode"];
    [_plateDic setValue:@"" forKey:@"plateName"];
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [_searchBar resignFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark- UITableViewDelegate / DataSource

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (clicknumber != indexPath) {
        clicknumber = indexPath;
    }else if (clicknumber == indexPath) {
        
        [_plateDic setValue:_plateArr[indexPath.row][@"plateCode"] forKey:@"plateCode"];
        [_plateDic setValue:_plateArr[indexPath.row][@"plateName"] forKey:@"plateName"];
        NSLog(@"%@",_plateDic);
        [self InquiryInventory];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"%lu",dataArr.count);
    return  _plateArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];//根据indexPath准确地取出一行，而不是从cell重用队列中取出
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.width = self.view.width;
    RZCustomLable *_warehouse = [[RZCustomLable alloc]initWithFrame:CGRectMake(0, 0, self.view.width/3, 50)];
    _warehouse.text = _plateArr[indexPath.row][@"plateCode"];
    _warehouse.numberOfLines = 0;
    _warehouse.textAlignment = UITextAlignmentCenter;
    _warehouse.textColor = [UIColor blackColor];
    [cell.contentView addSubview:_warehouse];
    
    RZCustomLable *code = [[RZCustomLable alloc]initWithFrame:CGRectMake(self.view.width/3, 0, self.view.width/3, 50)];
    code.text = _plateArr[indexPath.row][@"plateName"];
    code.numberOfLines = 0;
    code.textAlignment = UITextAlignmentCenter;
    code.textColor = [UIColor blackColor];
    [cell.contentView addSubview:code];
    
    _numLab = [[RZCustomButtom alloc]initWithFrame:CGRectMake(self.view.width/3*2 + self.view.width/6-25, 0, 60, 44)];
    [_numLab setTitle:[NSString stringWithFormat:@"%@",_plateArr[indexPath.row][@"plateCount"]] forState:(UIControlStateNormal)];
    _numLab.titleLabel.textAlignment = UITextAlignmentCenter;
    [_numLab setTitleColor:[UtilCheck hexStringToColor:@"40BFF5" alpha:1] forState:(UIControlStateNormal)];
    _numLab.tag = indexPath.row;
    [_numLab addTarget:self action:@selector(number:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.contentView addSubview:_numLab];
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(10,cell.height-0.5, self.view.width - 20, 0.5)];
    line.backgroundColor = [UtilCheck hexStringToColor:@"EcEcEc" alpha:1];
    [cell.contentView addSubview:line];
    return cell;
}
- (void)number:(UIButton *)sender {
    [_plateDic setValue:_plateArr[sender.tag][@"plateCode"] forKey:@"plateCode"];
    [_plateDic setValue:_plateArr[sender.tag][@"plateName"] forKey:@"plateName"];
    NSLog(@"%@",_plateDic);
    [self InquiryInventory];
}
#pragma mark- 网络请求
#pragma mark-

#pragma mark 库存查询
- (void)InquiryInventory {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
   
    [[BDHUD sharedManager] showBDHUD:self.view title:nil];
    
    [AFHttpTool postJsonDatawithUrl:@"shipmentSerialNumber"  parameters:_plateDic success:^(id responseObject) {
        NSLog(@"responseobject ----- %@",responseObject);
        [[BDHUD sharedManager] dismissHUD];
        
        if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue] && [[responseObject objectForKey:@"data"] isKindOfClass:[NSArray class]]) {
            NSArray *arr = [responseObject objectForKey:@"data"];
            SerialNumberVC *vc = [[SerialNumberVC alloc]init];
            vc.stockStr = @"1";
            vc.numberArr = arr;
            [self presentViewController:vc animated:YES completion:nil];
        }
        else {
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
        }
        
    } fail:^(id responseObject, NSError *error) {
        NSLog(@"%@",error);
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
}
#pragma mark- 其他事件
#pragma mark-

/**
 *  更改字符串的前两个空格之间字符串的颜色
 *
 *  @param txt 要改变颜色的字符床
 1231
 *
 *  @return 改变后的字符串
 */
- (NSMutableAttributedString *)attributedString:(NSString *)txt {
    
    // 查找出前两个空格的位置
    NSInteger start = 0;
    NSInteger end = 0;
    NSRange countRange = NSMakeRange(0, 0);
    
    for (int i = 0 ; i < txt.length; i ++) {
        if ([txt characterAtIndex:i] == 32 && start == 0) {
            start = i;
            
        }
        else if([txt characterAtIndex:i] == 32){
            end = i;
            countRange = NSMakeRange(start + 1, end - start);
            break;
        }
    }
    // 改变范围内字符颜色
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:txt];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:[UtilCheck hexStringToColor:@"40BFF5" alpha:1] range:countRange];
    return attributeStr;
}


@end
